<?php
    /**
     * Created by <xinxin.deng>.
     * Author: xinxin.deng
     * Date: 2018/10/31 10:48
     */
    namespace ns_model\delivery;

    include_once dirname(dirname(dirname(__FILE__)))."/common.php";
    \ns_core\m_load::load_old("nn_logic/pass_queue/pass_queue.class.php");
    \ns_core\m_load::load("ns_model.m_queue_model");
    \ns_core\m_load::load_np("np_http_curl.class.php");

    class pass_queue_delivery_explain
    {
        public $str_sp_id = '';//SPID
        public $str_source_id = '';//CPID
        public $arr_sp_config = array();//SP配置
        public $arr_source_config = array();//CP配置

        private $m_queue_model = array();
        private $pass_queue_task_info = array();//透传队列数据

        public function __construct($sp_id)
        {
            //创建DC
            \m_config::set_dc();
            if(strlen($sp_id) > 0 && !empty($sp_id))
            {
                $this->str_sp_id = $sp_id;
                $arr_sp_config = \m_config::_get_sp_info($this->str_sp_id);
                $this->arr_sp_config = isset($arr_sp_config['data_info']['nns_config']) ? $arr_sp_config['data_info']['nns_config'] : array();
            }

            //初始化底层队列运行方法
            $this->m_queue_model = new \ns_model\m_queue_model();
        }


        public function init($pass_queue_task_info = array())
        {
            $this->pass_queue_task_info = isset($pass_queue_task_info['pass_queue_task_info']) ? $pass_queue_task_info['pass_queue_task_info'] : array();

            //初始化cp信息
            if(isset($pass_queue_task_info['pass_queue_task_info']) && !empty($pass_queue_task_info['pass_queue_task_info']['nns_cp_id']))
            {
                $this->str_source_id = $pass_queue_task_info['pass_queue_task_info']['nns_cp_id'];
            }
            $arr_source_config = \m_config::_get_cp_info($this->str_source_id);
            $this->arr_source_config = isset($arr_source_config['data_info']['nns_config']) ? $arr_source_config['data_info']['nns_config'] : array();

        }

        /**
         * 获取透传任务类型
         * @return string
         */
        public function get_task_type()
        {
            if(!empty($this->pass_queue_task_info) && isset($this->pass_queue_task_info['nns_type']))
            {
                return $this->pass_queue_task_info['nns_type'];
            }
            return '';
        }

        /**
         * 根据key获取value
         * @param string $key
         * @return mixed|string
         * xinxin.deng 2018/10/31 11:37
         */
        public function get_pass_queue_task_info($key='')
        {
            if(empty($key))
            {
                return '';
            }
            if (strpos($key, 'nns_') === FALSE)
            {
                $key = 'nns_' . $key;
            }
            if(!empty($this->pass_queue_task_info) && isset($this->pass_queue_task_info[$key]))
            {
                return $this->pass_queue_task_info[$key];
            }
            return '';
        }

        /**
         * 获取DC
         * @return Object
         */
        public function get_dc()
        {
            return \m_config::get_dc();
        }

        /****************************透传队列分发执行开始*****************************/
        public function explain()
        {
            $pass_queue_type = $this->get_task_type();
            switch ($pass_queue_type)
            {
                case '0':
                    $re = $this->category_sync();//栏目同步
                    break;
                case '1':
                    $re = $this->category_recommend();//栏目推荐
                    break;
                case '2':
                    $re = $this->cp_sync();//cp同步
                    break;
                case '3':
                    $re = $this->category_img_sync();//栏目图片
                    break;
                case '4':
                    $re = $this->assets_fuse_sync();//媒资融合
                    break;
                case '5':
                    $re = $this->assets_package_sync();//媒资打包关系，走k23
                    break;
                case '6':
                    $re = $this->playbill_item_sync();//录制节目单,走k23
                    break;
                case '7':
                    $re = $this->assets_lock_sync();//媒资锁定解锁
                    break;
                case '50':
                    $re = $this->video_bind_sync();//主媒资绑定解绑
                    break;
                case '94':
                    $re = $this->mgtv_video_index_sync();//湖南花絮预告片与正片绑定关系
                    break;
                case '98':
                    $re = $this->mgtv_playbill_sync();//湖南节目单注入
                    break;
                case '99':
                    $re = $this->mgtv_live_lock_sync();//湖南直播频道锁定解锁
                    break;
                case '101':
                    $re = $this->cntv_asset_line_sync();//爱上项目，上下线注入到cdn
                    break;
                case '102':
                    $re = $this->video_or_index_modify_sync();//主媒资修改，走k23
                    break;
                case '103':
                    $re = $this->video_or_index_modify_sync();//分集修改
                    break;
                case '104':
                    $re = $this->start_sync();//明星库
                    break;
                default:
                    $re = array(
                        'ret' => NS_CDS_FAIL,
                        'reason' => '没有配置与之对应的透传对应类型。请在此文件配置' . __FILE__,
                    );
                    break;
            }
            return $this->save_exec_log($re);
        }

        /**
         * 栏目同步
         * @return array
         */
        public function category_sync()
        {
            $pass_queue_info = $this->pass_queue_task_info;
            if (strlen($pass_queue_info['nns_action'])<1)
            {
                return $this->write_log_return('没有没有行为动作【nns_action为空】', NS_CDS_FAIL);
            }

            //请求数据封装
            $info = array(
                'm' => 'sync_asset_category/k380_b_1',
                'a' => (int)$pass_queue_info['nns_action'] === 1 ? 'add' : 'delete', //1添加 3删除
            );
            $url = $this->arr_sp_config['pass_queue_import_url'] . '?' . http_build_query($info);
            $re = $this->post_data($url,array('data' => $pass_queue_info['nns_content']));

            return $this->is_ok($re['ret'], $re['reason']);
        }

        /**
         * 栏目推荐
         * @return array
         */
        public function category_recommend()
        {
            $pass_queue_info = $this->pass_queue_task_info;
            if ((int)$pass_queue_info['nns_action'] === 0 || (int)$pass_queue_info['nns_action'] == 2)
            {
                return $this->write_log_return('没有没有行为动作【nns_action为空】', NS_CDS_FAIL);
            }
            //请求数据封装
            $info = array(
                'm' => 'sync_asset_category/k380_a_1',
                'a' => (int)$pass_queue_info['nns_action'] === 1 ? 'maintain' : 'delete', //1添加 3删除
            );
            $url = $this->arr_sp_config['pass_queue_import_url'] . '?' . http_build_query($info);
            $re = $this->post_data($url,array('data' => $pass_queue_info['nns_content']));
            return $this->is_ok($re['ret'], $re['reason']);
        }

        /**
         * cp同步
         * @return array
         */
        public function cp_sync()
        {
            $pass_queue_info = $this->pass_queue_task_info;
            if ((int)$pass_queue_info['nns_action'] != 1)
            {
                return $this->write_log_return('没有没有行为动作【nns_action为空】', NS_CDS_FAIL);
            }
            //请求数据封装
            $info = array(
                'm' => 'sync_asset_category/k381_a_1',
                'a' => 'add', //1添加
            );
            $url = $this->arr_sp_config['pass_queue_import_url'] . '?' . http_build_query($info);
            $re = $this->post_data($url,array('data' => json_decode($pass_queue_info['nns_content'])));
            return $this->is_ok($re['ret'], $re['reason']);
        }

        /**
         * 栏目图片同步
         * @return array
         */
        public function category_img_sync()
        {
            $pass_queue_info = $this->pass_queue_task_info;
            if ((int)$pass_queue_info['nns_action'] === 0 || (int)$pass_queue_info['nns_action'] == 2)
            {
                return $this->write_log_return('没有没有行为动作【nns_action为空】', NS_CDS_FAIL);
            }
            //请求数据封装
            $info = array(
                'm' => 'sync_asset_category/k380_a_1',
                'a' => (int)$pass_queue_info['nns_action'] === 1 ? 'add_img' : 'delete_img', //1添加 3删除
            );
            $url = $this->arr_sp_config['pass_queue_import_url'] . '?' . http_build_query($info);
            $re = $this->post_data($url,array('data' => $pass_queue_info['nns_content']));
            return $this->is_ok($re['ret'], $re['reason']);
        }

        /**
         * 媒资融合
         * @return array
         */
        public function assets_fuse_sync()
        {
            $pass_queue_info = $this->pass_queue_task_info;

            //请求数据封装
            $info = array(
                'm' => 'fusion_assets/k382_a_1',
                'a' => 'record_data_to_database',
                'bk_msg_id' => $pass_queue_info['nns_id']
            );
            $url = $this->arr_sp_config['pass_queue_import_url'] . '?' . http_build_query($info);
            $re = $this->post_data($url,array('data' => $pass_queue_info['nns_content']));
            return $this->is_ok($re['ret'], $re['reason']);
        }

        /**
         * 媒资打包关系
         * @return array
         */
        public function assets_package_sync()
        {
            $pass_queue_info = $this->pass_queue_task_info;

            //解析获取assetid
            $obj = simplexml_load_string($pass_queue_info['nns_content']);
            $asset_info = json_decode(json_encode($obj), true);
            if(empty($asset_info["@attributes"]['assets_id']))
            {
                return$this->write_log_return('打包关系解析失败', NS_CDS_FAIL);
            }
            $asset_id = $asset_info["@attributes"]['assets_id'];

            //请求数据封装
            $info = array(
                'func' => 'modify_video',
                'assets_content' => $pass_queue_info['nns_content'],
                'assets_video_info' => $pass_queue_info['nns_content'],
                'asset_source_id' => $asset_id,
                'assets_id' => $asset_id,
            );
            $url = $this->arr_sp_config['epg_url'];
            $re = $this->post_data($url, $info);
            return $this->is_ok($re['ret'], $re['reason']);
        }

        /**
         * 节目单走k23
         * @return array
         */
        public function playbill_item_sync()
        {
            $pass_queue_info = $this->pass_queue_task_info;
            //请求数据封装
            $info = array(
                'func' => 'import_vod_playbill',
                'playbill' => $pass_queue_info['nns_content'],
            );
            $url = $this->arr_sp_config['epg_url'];
            $re = $this->post_data($url, $info);
            if ($re['ret'] != NS_CDS_SUCCE)
            {
                return $this->is_ok($re['ret'], $re['reason']);
            }

            //解析k23反馈数据
            $result_notify = json_decode(json_encode(@simplexml_load_string($re['data_info'])),true);
            if($result_notify['@attributes']['ret'] != NS_CDS_EPG_NOTIFY_SUCCE && $result_notify['@attributes']['ret'] != NS_CDS_EPG_NOTIFY_NOTFOUND)
            {
                $epg_code = NS_CDS_FAIL;
            }
            else
            {
                $epg_code = NS_CDS_SUCCE;
            }

            return $this->is_ok($epg_code, $result_notify['@attributes']['reason']);
        }

        /**
         * 媒资锁定解锁
         * @return array
         */
        public function assets_lock_sync()
        {
            $pass_queue_info = $this->pass_queue_task_info;
            $lock_info = json_decode($pass_queue_info['nns_content'], true);
            //请求数据封装
            $info = array(
                'func' => 'lock_and_unlock_asset',
                'cp_id' => $lock_info[0]['cp_id'],
                'assets_id' => $lock_info[0]['assets_id'],
                'check' => $lock_info[0]['check'],
                'assets_id_type' => $lock_info[0]['assets_id_type'],
            );
            $url = $this->arr_sp_config['epg_url'];
            $re = $this->post_data($url, $info);
            return $this->is_ok($re['ret'], $re['reason']);
        }

        /**
         * 主媒资绑定或解绑定分集
         * @return array
         */
        public function video_bind_sync()
        {
            $pass_queue_info = $this->pass_queue_task_info;
            $obj = simplexml_load_string($pass_queue_info['nns_content']);
            $arr_index_bind_info = json_decode(json_encode($obj), true);
            if(!isset($arr_index_bind_info['assets_id']) || strlen($arr_index_bind_info['assets_id']) < 1)
            {
                return$this->write_log_return('主媒资与分集绑定关系中，主媒资ID不存在', NS_CDS_FAIL);
            }
            $str_assets_id = $arr_index_bind_info['assets_id'];
            //请求数据封装
            $info = array(
                'func' => 'bind_vod_index',
                'assets_id' => $str_assets_id,
                'vod_index_list' => $pass_queue_info['nns_content'],
            );
            $url = $this->arr_sp_config['epg_url'];
            $re = $this->post_data($url, $info);
            return $this->is_ok($re['ret'], $re['reason']);
        }

        /**
         * 湖南电信/联通花絮预告和正片的绑定关系
         * @return array
         */
        public function mgtv_video_index_sync()
        {
            $pass_queue_info = $this->pass_queue_task_info;
            //请求数据封装
            $info = array(
                'func' => 'import_video_index_bind',
            );

            $data = array('data'=>$pass_queue_info['nns_content']);
            $data = array_merge($info,$data);
            $url = $this->arr_sp_config['epg_url'];
            $re = $this->post_data($url, $data);
            if ($re['ret'] != NS_CDS_SUCCE)
            {
                return $this->is_ok($re['ret'], $re['reason']);
            }

            //解析k23反馈数据
            $result_notify = json_decode(json_encode(@simplexml_load_string($re['data_info'])),true);
            if($result_notify['@attributes']['ret'] != NS_CDS_EPG_NOTIFY_SUCCE && $result_notify['@attributes']['ret'] != NS_CDS_EPG_NOTIFY_NOTFOUND)
            {
                $epg_code = NS_CDS_FAIL;
            }
            else
            {
                $epg_code = NS_CDS_SUCCE;
            }

            return $this->is_ok($epg_code, '[epg注入]' . $result_notify['@attributes']['reason']);
        }

        /**
         * 湖南电信/联通直播节目单注入
         * @return array
         */
        public function mgtv_playbill_sync()
        {
            $pass_queue_info = $this->pass_queue_task_info;
            $info = array(
                'func' => 'import_playbill_by_json',
                'bk_message_id' => $pass_queue_info['nns_id'],
                'identify' => 'live_ex=live_id|key=hndx_upstream_live_id|value=?',
            );
            $data = array('data'=>$pass_queue_info['nns_content']);
            $data = array_merge($info,$data);
            $url = $this->arr_sp_config['epg_url'];
            $re = $this->post_data($url, $data);
            return $this->is_ok($re['ret'], $re['reason']);
        }

        /**
         * 湖南电信/联通直播频道锁定解锁
         * @return array
         */
        public function mgtv_live_lock_sync()
        {
            $pass_queue_info = $this->pass_queue_task_info;
            //请求数据封装
            $info = array(
                'm' => 'k24/k24_c_1',
                'a' => 'option_live_lock_state',
            );
            $url = $this->arr_sp_config['pass_queue_import_url'] . '?' . http_build_query($info);
            $re = $this->post_data($url,array('data' => $pass_queue_info['nns_content']));
            return $this->is_ok($re['ret'], $re['reason']);
        }

        //爱上上下线注入cdn---后面根据项目在项目进行封装
        public function cntv_asset_line_sync()
        {
            return $this->is_ok(NS_CDS_SUCCE, '');
        }

        /**
         * 主媒资或者分集的修改-走k23
         * @return array
         */
        public function video_or_index_modify_sync()
        {
            $pass_queue_info = $this->pass_queue_task_info;
            $info = json_decode($pass_queue_info['nns_content'], true);
            $url = $this->arr_sp_config['epg_url'];
            $re = $this->post_data($url, $info);

            if ($re['ret'] != NS_CDS_SUCCE)
            {
                return $this->is_ok($re['ret'], $re['reason']);
            }

            //解析k23反馈数据
            $result_notify = json_decode(json_encode(@simplexml_load_string($re['data_info'])),true);
            if($result_notify['@attributes']['ret'] != NS_CDS_EPG_NOTIFY_SUCCE && $result_notify['@attributes']['ret'] != NS_CDS_EPG_NOTIFY_NOTFOUND)
            {
                $epg_code = NS_CDS_FAIL;
            }
            else
            {
                $epg_code = NS_CDS_SUCCE;
            }

            return $this->is_ok($epg_code, '[epg注入]' . $result_notify['@attributes']['reason']);
        }

        /**
         * 明星库注入
         * @return array
         */
        public function start_sync()
        {
            $pass_queue_info = $this->pass_queue_task_info;
            $info = json_decode($pass_queue_info['nns_content'], true);
            $url = $this->arr_sp_config['epg_url'];
            $re = $this->post_data($url, $info);
            return $this->is_ok($re['ret'], $re['reason']);
        }


        /**
         * 注入
         * @param $url //请求地址
         * @param $data //请求数据
         * @return array('ret'=>'状态码','reason'=>'原因','data'=>'数据')|multitype:number
         */
        public function post_data($url, $data)
        {
            if(empty($url) || empty($data))
            {
                return $this->write_log_return("注入EPG入参地址或参数错误",NS_CDS_FAIL);
            }
            $curl = new \np_http_curl_class();
            $curl_ret = $curl->post($url,$data);
            $curl_info = $curl->curl_getinfo();
            if($curl_info['http_code'] != '200')
            {
                return $this->write_log_return('EPG注入失败,HTTP状态码'.$curl_info['http_code'],NS_CDS_FAIL);
            }
            $this->write_log_return("CURL成功");
            return \m_config::return_data(NS_CDS_SUCCE,'',$curl_ret);
        }

        /**
         * 统一透传回调
         * @param $code 0成功 1失败 详见m_const常量
         * @param string $reason 描述
         * @return array
         */
        public function is_ok($code, $reason='')
        {
            $pass_queue_task_info = $this->pass_queue_task_info;

            //根据注入反馈的状态将task的状态设置为失败或成功
            if($code != 0)
            {
                $re = \nl_pass_queue::modify($this->get_dc(), array('nns_status' => 3), array('nns_id' => $pass_queue_task_info['nns_id']));
            }
            elseif ($code == 0 && ($pass_queue_task_info['nns_type'] == '4' || $pass_queue_task_info['nns_type'] == '98'))
            {
                $re = \nl_pass_queue::modify($this->get_dc(), array('nns_status' => 4), array('nns_id' => $pass_queue_task_info['nns_id']));
            }
            else
            {
                $re = \nl_pass_queue::modify($this->get_dc(), array('nns_status' => 0), array('nns_id' => $pass_queue_task_info['nns_id']));
            }

            if($re['ret'] != NS_CDS_SUCCE)
            {
                return $this->write_log_return('修改透传队列状态失败' . $re['reason'], $re['ret']);
            }

            //封装成统一样式数组
            $data = array(
                'site_id' => $this->arr_sp_config['site_id'],
            );
            //定义类型走的反馈模式
            $type_arr = array(
                '7',
                '94',
                '98',
                '99',
            );
            $format = in_array($pass_queue_task_info['nns_type'], $type_arr) ? 'json' : 'xml';

            \ns_core\m_msg_callback::is_ok_v2($pass_queue_task_info['nns_cp_id'], $pass_queue_task_info['nns_message_id'], $code, $reason, $data, $pass_queue_task_info, $format);

            return $this->write_log_return($reason);
        }

        public function notify($c2_correlate_id, $code, $result_url)
        {

            return $this->is_notify_ok($c2_correlate_id, $code, '', '');
        }

        /**
         * 透传队列异步回调注入状态
         * @param $c2_correlate_id //c2注入交互信令唯一ID
         * @param $code //详见m_const常量
         * @param string $reason 描述
         * @param string $notify_result 下游反馈的原始数据
         * @return array
         */
        public function is_notify_ok($c2_correlate_id, $code, $reason, $notify_result='')
        {
            if(empty($c2_correlate_id))
            {
                return $this->write_log_return("CDN回调未传递工单唯一表标识ID",NS_CDS_FAIL);
            }

            return $this->is_ok($code,$reason);
        }

        /**
         * 透传队列执行日志记录
         * @param $return_info
         * @return mixed
         */
        public function save_exec_log($return_info)
        {
            if($this->get_pass_queue_task_info('id'))
            {
                if (isset($return_info['data_info']['base_dir']) && !empty($return_info['data_info']['base_dir']))
                {
                    $exec_log = array("nns_queue_execute_url" => $return_info['data_info']['base_dir']);
                    //修改透传任务
                    \nl_pass_queue::modify($this->get_dc(), $exec_log, array('nns_id' => $this->get_pass_queue_task_info('id')));
                }
                elseif (isset($return_info['error_data_info']['base_dir']) && !empty($return_info['error_data_info']['base_dir']))
                {
                    $exec_log = array("nns_queue_execute_url" => $return_info['error_data_info']['base_dir']);
                    //修改透传任务
                    \nl_pass_queue::modify($this->get_dc(), $exec_log, array('nns_id' => $this->get_pass_queue_task_info('id')));
                }
            }
            return $return_info;
        }

        /**
         * 根据参数记录日志，并返回
         * @param string $msg 文字消息
         * @param int $code 状态码，默认成功0
         * @return array()
         */
        public function write_log_return($msg, $code=NS_CDS_SUCCE)
        {
            //来源ID、SPID、C2有值，则存CDN队列日志 queue_log
            if(!empty($this->get_pass_queue_task_info('org_id')) && !empty($this->c2_info) && !empty($this->get_pass_queue_task_info('id')))
            {
                $ret = \m_config::write_pass_queue_execute_log($msg, $this->get_pass_queue_task_info('org_id'), $this->get_pass_queue_task_info('id'));
            }
            else //存入公共日志  global_log
            {
                $ret = \m_config::write_global_execute_log(NS_CDS_PASS_QUEUE,$this->str_source_id,$this->str_sp_id,$this->get_pass_queue_task_info('action'),$this->get_pass_queue_task_info(),var_export($msg,true));
            }

            return \m_config::return_data($code, $msg, $ret['data_info']);
        }


        public function destroy_init()
        {
            unset($this->pass_queue_task_info);
            unset($this->str_source_id);
            unset($this->arr_source_config);
        }
    }